package com.skd.mall.cart.service.Impl;

import com.alibaba.fastjson.JSON;
import com.skd.common.constant.CartConstant;
import com.skd.common.utils.R;
import com.skd.common.vo.MemberVO;
import com.skd.mall.cart.feign.ProductFeignService;
import com.skd.mall.cart.interceptor.AuthInterceptor;
import com.skd.mall.cart.service.ICartService;
import com.skd.mall.cart.vo.Cart;
import com.skd.mall.cart.vo.CartItem;
import com.skd.mall.cart.vo.SkuInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service
public class ICartServoceImpl implements ICartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    /**
     * 查询当前用户的购物车的信息
     * @return
     */
    public Cart getCartList(){
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        Set<Object> keys = cartKeyOperation.keys();
        Cart cart = new Cart();
        ArrayList<CartItem> list = new ArrayList<>();
        for (Object k : keys) {
            String key = (String) k;
            Object o = cartKeyOperation.get(key);
            String json = (String) o;
            CartItem item = JSON.parseObject(json, CartItem.class);
            list.add(item);
        }
        cart.setItems(list);
        return cart;
    }

    @Override
    public CartItem addCart(String skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        Object o = cartKeyOperation.get(skuId);
        //如果已经在购物车中存在商品，直接修改数量即可
        if(o!=null){
            String json = (String) o;
            CartItem cartItem = JSON.parseObject(json, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartKeyOperation.put(skuId,JSON.toJSONString(cartItem));
            return cartItem;
        }

        CartItem cartItem = new CartItem();
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            //1远程调用查询sku信息
            R r = productFeignService.info(Long.parseLong(skuId));
            String skuInfoJson = (String) r.get("skuInfoJson");
            SkuInfoVO skuInfoVO = JSON.parseObject(skuInfoJson,SkuInfoVO.class) ;
            cartItem.setCheck(true);
            cartItem.setSkuId(skuInfoVO.getSkuId());
            cartItem.setSpuId(skuInfoVO.getSpuId());
            cartItem.setPrice(skuInfoVO.getPrice());
            cartItem.setImage(skuInfoVO.getSkuDefaultImg());
            cartItem.setCount(num);
            cartItem.setTitle(skuInfoVO.getSkuTitle());
        }, threadPoolExecutor);
        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            //2查询销售属性
            List<String> attrs = productFeignService.getAttrsBySkuId(Long.parseLong(skuId));
            cartItem.setSkuAttr(attrs);
        }, threadPoolExecutor);

        CompletableFuture.allOf(future1,future2).get();
        //3保存到redis中
        String jsonString = JSON.toJSONString(cartItem);
        cartKeyOperation.put(skuId,jsonString);
        return cartItem;
    }

    @Override
    public void deleteCartList(Long skuId) {
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        Long delete = cartKeyOperation.delete(String.valueOf(skuId));
    }


    @Override
    public List<CartItem> getUserCartItem() {
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        List<Object> values = cartKeyOperation.values();
        List<CartItem> list = values.stream().map(item -> {
            String s = String.valueOf(item);
            CartItem cartItem = JSON.parseObject(s, CartItem.class);
            return cartItem;
        }).filter(item -> {
            return item.isCheck();
        }).collect(Collectors.toList());
        return list;
    }

    @Transactional
    @Override
    public void updateCartList(List<Long> skuIdList) {
        BoundHashOperations<String, Object, Object> cartKeyOperation = getCartKeyOperation();
        for (Long skuId : skuIdList) {
            Long delete = cartKeyOperation.delete(String.valueOf(skuId));
        }
    }

    //获得登录信息并写入redis
    private BoundHashOperations<String, Object, Object> getCartKeyOperation() {
        MemberVO memberVO = AuthInterceptor.threadLocal.get();
        String id = String.valueOf(memberVO.getId());
        String cartKey = CartConstant.CART_PERFIX+id;
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(cartKey);
        return hashOperations;
    }



}
